import { GImage } from './GImage';

//动画
export class GAnimation {
    images: GImage[];
    timespan: number;

    framespan: number;//每帧应该的时间跨度
    current: number = 0;//默认第0帧

    running: boolean = false;
    loop: boolean = false;


    reset: boolean = true;//是否重置(默认为true)
    start: number;//起始时间


    constructor(images: GImage[], timespan: number) {

        if (images.length === 0) {
            throw new Error('动画至少应由一张图片组成');
        }

        this.images = images;
        this.timespan = timespan;
        //每帧应该持续多久
        this.framespan = (this.timespan / this.images.length);
    }

    //播放
    play() {
        //播放
        this.reset = true;
        this.running = true;
    }
    //停止
    stop() {
        this.running = false;
    }

    //恢复
    resume() {
        //恢复
        this.running = true;
    }
    //暂停
    pause() {
        //暂停
        this.running = false;
    }

    update(timespan: number) {
        //动画的更新函数

    }

    //draw
    draw(canvas: HTMLCanvasElement): void {

        //是否重置
        if (this.reset) {
            this.current = 0;
            this.start = new Date().getTime();
            this.reset = false;
        }

        //计算时间差
        let diff = new Date().getTime() - this.start;
        if (diff >= this.framespan) {
            this.current++;
            this.start = new Date().getTime();
        }

        //从第一帧开始播放
        if (this.current > (this.images.length - 1)) {
            this.current = 0;
            this.start = new Date().getTime();
        }

        //绘图
        this.images[this.current].draw(canvas);

    }
}